Functions and exceptions

Functions

Write a function that converts from Celsius to Kelvin.

To convert from Centigrade to Kelvin you add 273.15 to the value.

Try your solution for a few values.


In [ ]:
def celsius_to_kelvin(c):
    return c + 273.15

celsius_to_kelvin(0)

Now write another function to convert from Fahrenheit to Celsius.

The formulato do so is

C = 5/9*(F-32)

Again, verify that your function does what is expected.


In [ ]:
def fahrenheit_to_celsius(f):
    return 5/9*(f-32)

fahrenheit_to_celsius(0)

Now make a function to convert from Fahrenheit to Kelvin.

Before you start coding, stop to think for a second. You can actually re-use the two other functions you have made. Fahrenheit to Kelvin can be represented as Fahrenheit to Celsius followed by Celsius to Kelvin.


In [ ]:
def fahrenheit_to_kelvin(f):
    return celsius_to_kelvin(fahrenheit_to_celsius(f))

fahrenheit_to_kelvin(0)

Finally, implement a more general conversion function that takes as arguments also the input and output scales, e.g. from_scale and to_scale. Provide default values for from_scale and to_scale, and call the function with different number of arguments. Try to call the function using both positional and keyword arguments. Which approach is more readable for you?


In [ ]:
def temperature_converter(value, from_scale='C', to_scale='K'):
    if from_scale == 'C' and to_scale == 'K':
        return celsius_to_kelvin(value)
    elif from_scale == 'F' and to_scale == 'C':
        return fahrenheit_to_celsius(value)
    elif from_scale == 'F' and to_scale == 'K':
        return fahrenheit_to_kelvin(value)
    else:
        raise NotImplementedError('Unknown conversion: {} -> {}'.format(from_scale, to_scale))
        
t = temperature_converter(25.2, from_scale='F')
print(t)

Exceptions

Ok, here's some code that fails. Find out at least 2 errors it raises by giving different inputs.

Then construct a try-except clause around the lines of code.


In [ ]:
try:
    var = float(input("give a number"))
    divided = 1/var
except TypeError:
    print("user didn't give a number")
except ZeroDivisionError:
    print("user divided by zero")

The open function is used to open files for reading or writing. We'll get to that but first let's try to open a file that doesn't exist.

Filesystem related errors are very common. A file might not exist or for some reason the user might not have the rights to open the file. Go ahead and make a try-except clause to catch this error.


In [ ]:
try:
    file_handle = open("i_dont_exist", "r")
except FileNotFoundError:
    print("file not found")

Compound

Implement the three remaining functions so you can convert freely between Fahrenheit and Kelvin.

Now look at the temperature_converter function. Try to figure out what errors malformed user input can cause. You can either wrap the function call in a try-except or you can wrap parts of the function.

If you have time you can increase the complexity of the function to cover centigrade conversions as well but this is not required. Hint: if you always convert the value to centigrade if it is not and to the desired output if desired output is not you can simplify the code.


In [ ]:
def celsius_to_fahrenheit(c):
    pass

def kelvin_to_celsius(k):
    pass

def kelvin_to_fahrenheit(k):
    pass

def temperature_converter():
    from_scale = input("Give scale to convert from: ")
    to_scale = input("Give scale to convert to: ")
    try:
        value = float(input("Give temperature: "))
    except TypeError:
        print("user didn't give a number")
        return
    if from_scale == "K" and to_scale == "F":
        return kelvin_to_fahrenheit(value)
    elif from_scale == "F" and to_scale == "K":
        return fahrenheit_to_kelvin(value)
    elif from_scale == "C" or to_scale == "C":
        raise NotImplementedError("Conversion to Centigrade not implemented!")
    return

temperature_converter()